package com.lcm.weam.util;

import com.lcm.weam.entity.exception.CommonException;
import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.security.GeneralSecurityException;
import java.util.Properties;

/**
 * 发送邮件的工具类
 */
public class JavaEmailUtil {
    private static final String SENDER = "805862573@qq.com";
    private static final String HOST = "smtp.qq.com";
    private static final String CODE = "ybbxmbjawsljbbdb";

    public static void sandMail(String title, String to, MimeMultipart multipart) throws MessagingException {
        Properties properties = new Properties();
        properties.setProperty("mail.host", HOST);
        properties.setProperty("mail.transport.protocol", "smtp");
        properties.setProperty("mail.smtp.auth", "true");
        //SSL加密
        try {
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            properties.put("mail.smtp.ssl.enable", "true");
            properties.put("mail.smtp.ssl.socketFactory", sf);
        } catch (GeneralSecurityException e) {
            throw new CommonException("生成MailSSLSocketFactory失败");
        }
        //创建一个session对象用于发送至smtp服务器
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(SENDER, CODE);
            }
        });
        //获取连接对象
        Transport transport = session.getTransport();
        transport.connect(HOST, SENDER, CODE);
        MimeMessage mimeMessage = getMimeMessage(session, title, to, multipart);
        //发送邮件
        transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
        //关闭连接
        transport.close();
    }

    private static MimeMessage getMimeMessage(Session session, String title, String to, MimeMultipart multipart) throws MessagingException {
        //创建邮件对象
        MimeMessage mimeMessage = new MimeMessage(session);
        //邮件发送人
        mimeMessage.setFrom(new InternetAddress(SENDER));
        //邮件接收人
        mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
        //邮件标题
        mimeMessage.setSubject(title);
        //配接内容
        mimeMessage.setContent(multipart);
        mimeMessage.saveChanges();
        return mimeMessage;
    }

}
